<?php

namespace catchAdmin\basics\service;


use catchAdmin\basics\model\Provider;
use catchAdmin\product\model\Product;
use catchAdmin\stock\model\MoveMain;
use catchAdmin\storehouse\model\WarehouseOut;
use catchAdmin\storehouse\model\WarehouseOutSon;
use catchAdmin\storehouse\model\Warehousing;
use catchAdmin\storehouse\model\WarehousingSon;
use think\console\Input;
use think\console\Output;
use think\Exception;
use think\facade\Cache;
use think\facade\Db;
use think\facade\Request;
use catcher\CatchAuth;


class EdiService{


    public function pathToDb($file_path){
        //清空之前的值
        $file_edi = '';
        $oneFileAllData = [];

        $file_content = file_get_contents($file_path);
        if ($file_content === false) throw new Exception('文件错误');

        // 将文件内容按行拆分
        $lines = explode(PHP_EOL, $file_content);



        $oneFileAllData = [];
        foreach ($lines as $key => $line) {
            if (trim($line) === '') continue; // 跳过空行
            $line = str_replace("\r", "", $line);$fields = explode("\t", $line);// 将每一行按一个制表符拆分成数组
            $oneFileAllData[] = $fields;
        }

//        判断文件字段个数来判断是什么文件
        $keyCounts = count($oneFileAllData[0]);

        //throw new Exception($keyCounts);

        if(42 == $keyCounts || 43 == $keyCounts){
            $file_name = 'SD032Oj'; //其他发货单
        }elseif (68 == $keyCounts || 69 == $keyCounts){
            $file_name = 'SD003Oj'; //销售发货单
        }elseif (33 == $keyCounts){
            $file_name = 'MM012Oj'; //收货单===入库单
        }else{
            throw new Exception('该文件类型赞不支持导入');
        }

        if($file_name == 'MD001Oj1'){
            $file_edi = 'customer';
        }elseif ($file_name == 'MD001Oj2'){
            $file_edi = 'vendor';
        }elseif ($file_name == 'MD001Oj3'){
            $file_edi = 'material';
        }elseif ($file_name == 'MM012Oj'){//收货单
            $file_edi = 'asn';
        }elseif ($file_name == 'SD003Oj'){//销售发货
            $file_edi = 'SD003Oj';
        }elseif ($file_name == 'SD032Oj'){//其他发货
            $file_edi = 'SD032Oj';
        }elseif ($file_name == 'MM009Oj'){//一步移仓
            $file_edi = 'MM009Oj';
        }

//        return  $oneFileAllData;

        $oneFileAllData = [];
        if($file_edi == 'asn' || $file_edi == 'SD003Oj' || $file_edi == 'SD032Oj' || $file_edi == 'MM009Oj'){
            foreach ($lines as $key => $line) {
                if (trim($line) === '') continue; // 跳过空行
                $line = str_replace("\r", "", $line);$fields = explode("\t", $line);// 将每一行按一个制表符拆分成数组
                $oneFileAllData[] = $fields;
            }
            $this->$file_edi($oneFileAllData);//写入数据
        } else{
            foreach ($lines as $key => $line) {
                if (trim($line) === '') continue; // 跳过空行

                $line = str_replace("\r", "", $line);$fields = explode("\t", $line);// 将每一行按一个制表符拆分成数组
                $this->$file_edi($fields);//写入数据
            }
        }


    }

    //客户
    private function customer($data){
        if($data[3] == 'Sold-to'){
            $role = 24;
        }elseif ($data[3] == 'Ship-to'){
            $role = 25;
        }elseif ($data[3] == 'Bill-to'){
            $role = 26;
        }else{
            $role = 0;
        }

        $account_code = $data[2];
        $_data = [
            'account_code' => $account_code,//客户代码
            'account_name' => $data[4],//客户名称
            'account_key' => $data[4],//客户简称
            'role'=>$role,//角色
            'zip_code' => $data[9],//邮编
            'prov' => $data[10],//省 州
            'city'=>$data[11],//城市
            'addr' => $data[15],//地址
            'relation_phone'=>$data[16],//联系电话
            'country'=>$data[20],//国家代码
        ];

        //$user = $auth->user();
        $_data['creator_id'] = 10148;
        $_data['tenant_id'] = 10148;

        $model = new Provider;
        //判断新增还是修改还是删除
        if(3 == $data[0]){//删除
            $result =  $model->where('account_code',$account_code)->where('role',$_data['role'])->delete();
        }else{
            $exist = $model->where('account_code',$account_code)->where('role',$_data['role'])->find();
            if($exist){
                $_data['updated_at'] = time();
                $result =  $model->where('account_code',$account_code)->where('role',$_data['role'])->save($_data);
            }else{
                $result =  $model->storeBy($_data);
            }
        }

        if(3 != $data[0]){
            if($result){
                writeOperationLogByCommand( '成功' ,'EDI/EdiToCross/SUCCESS/customer');
                return true;
            }else{
                writeOperationLogByCommand( '失败' . json_encode($data,JSON_UNESCAPED_UNICODE) ,'EDI/EdiToCross/ERROR/customer');
                return false;
            }
        }
    }

    //供应商
    private function vendor($data){
        $account_code = $data[3];
        $_data = [
            'account_code' => $account_code,//客户代码
            'account_name' => $data[6],//客户名称
            'account_key' => $data[6],//客户简称
            'role'=>22,//角色 = 供应商
            'zip_code' => $data[11],//邮编
            'prov' => $data[12],//省 州
            'city'=>$data[13],//城市
            'addr' => $data[17],//地址
//            'relation_phone'=>$data[16],//联系电话
            'country'=>$data[22],//国家代码
        ];

        //$user = $auth->user();
        $_data['creator_id'] = 10148;
        $_data['tenant_id'] = 10148;

        $model = new Provider;
        //判断新增还是修改还是删除
        if(3 == $data[0]){//删除
            $result =  $model->where('account_code',$account_code)->where('role',$_data['role'])->delete();
        }else{
            $exist = $model->where('account_code',$account_code)->where('role',$_data['role'])->find();
            if($exist){
                $_data['updated_at'] = time();
                $result =  $model->where('account_code',$account_code)->where('role',$_data['role'])->save($_data);
            }else{
                $result =  $model->storeBy($_data);
            }
        }

        if(3 != $data[0]){
            if($result){
                writeOperationLogByCommand( '成功' ,'EDI/EdiToCross/SUCCESS/vendor');
                return true;
            }else{
                writeOperationLogByCommand( '失败' . json_encode($data,JSON_UNESCAPED_UNICODE) ,'EDI/EdiToCross/ERROR/vendor');
                return false;
            }
        }
    }

    //物料
    private function material($data){
        ini_set('memory_limit', '4086M');
        $goods_name = $data[2];

//        if($goods_name == 'B00F2021005'){
//            dd($data);
//        }


        $rand =  mt_rand(1000,9999) .mt_rand(1000,9999);
        $date = date('YmdHis');
        $_data = [
            'goods_id'=> $date . $rand,
            'goods_name' => $data[2],//商品编号
            'goods_Cname' => $data[3],//中文名
            'goods_Ename' => $data[3],//英文名
            'sku' => $data[2] . '/' . $data[3],//sku
            'company'=>$data[8],//单位
            'packing_id'=>'2024062615184510148',//默认包装 一拖一箱一件
//            'zip_code' => $data[11],//邮编
//            'prov' => $data[12],//省 州
//            'city'=>$data[13],//城市
//            'addr' => $data[17],//地址
////            'relation_phone'=>$data[16],//联系电话
//            'country'=>$data[22],//国家代码
        ];

        //$user = $auth->user();
        $_data['creator_id'] = 10148;
        $_data['tenant_id'] = 10148;

        //dump($_data);die();

        $model = new Product;
        //判断新增还是修改还是删除
        if(3 == $data[0]){//删除
            $result =  $model->where('goods_name',$goods_name)->delete();
        }else{
            $exist = $model->where('goods_name',$goods_name)->find();
            if($exist){
                $_data['updated_at'] = time();
                $result =  $model->where('goods_name',$goods_name)->save($_data);
            }else{
                $result =  $model->storeBy($_data);
            }
        }

        if(3 != $data[0]){
            if($result){
                writeOperationLogByCommand( '成功' ,'EDI/EdiToCross/SUCCESS/material');
                return true;
            }else{
                writeOperationLogByCommand( '失败' . json_encode($data,JSON_UNESCAPED_UNICODE) ,'EDI/EdiToCross/ERROR/material');
                return false;
            }
        }
    }

    //销售发货
    private function SD003Oj($data){
        ini_set('memory_limit', '4086M');

        Db::startTrans();
        try {
            // 使用array_reduce进行分组
            $chunk_data = array_reduce($data, function($reduce_arr, $item) {
                $item_code = $item[0];
                $reduce_arr[$item_code][] = $item;
                return $reduce_arr;
            }, []);

            foreach ($chunk_data as $_code => $_data){
                $warehouseOutModel = new WarehouseOut;
                //判断业务单号是否存在
                $record_pk =  $warehouseOutModel->where('customer_business_number',$_code)->value('id');
                if($record_pk > 0) continue; //存在

                //判断项目是成都还是西安
                $_project_id = '202406261542166632';
                if(in_array($_data[0][16],[6201,6213,6214,6210])){
                    $_project_id = '202407090933417657';
                }

                $params = [
                    'goods_number'=> (int) array_sum(array_column($_data,58) ),
                    'new_order_date'=>date("Y-m-d"),
                    'project_id'=>['202406261520274958',$_project_id],
                    'transport_type'=>'陆运',
                    'customer_business_number' => $_code
                ];

                $params['tenant_id'] =10148;
                $params['project_client'] = $params['project_id'][1];
                $params['project_id'] = $params['project_id'][0];
                if(!empty($params['ship_to_city'])){
                    $params['ship_to_city'] = json_encode($params['ship_to_city']);
                }
                if(!empty($params['shipper_city'])){
                    $params['shipper_city'] = json_encode($params['shipper_city']);
                }
                $params['warehouse_out_id'] = $params['tenant_id'] . date('YmdHis');
                $params['edi_json'] = json_encode($_data,JSON_UNESCAPED_UNICODE);

                $warehouseOutSonModel = new WarehouseOutSon;

                $pk = $warehouseOutModel->storeBy($params);

                $out_return = $warehouseOutModel->findBy($pk);
                $warehouse_out_id = $out_return['warehouse_out_id'];

                //出库子单
                $warehouse_out_son_arr  = [];
                foreach ($_data as $_k =>  $_d1){
                    $warehouse_out_son_data = [
//                        'box_number'=>1,
                        'box_number'=>$_d1[58],
                        'number'=>$_d1[58],
//                    'packing_id'=>[$_d1[56],'2024062615184510148'],
                        'warehouse_out_id'=>$warehouse_out_id,
                        'warehousing_select_no'=>[],
                        'tenant_id'=>10148,
                        'goods_name'=>$_d1[56],
                        'goods_id'=> Db::table('db_product')
                                ->where('goods_name',$_d1[56])
                                ->where('tenant_id',10148)
                                ->value('goods_id') ?? '',
                        'packing_id'=>'2024062615184510148',
                        'warehouse_out_son_id'=> '10148' . date('YmdHis') .mt_rand(1000,9999).mt_rand(1000,9999) . $_k,
                        'edi_json' => json_encode($_d1,JSON_UNESCAPED_UNICODE),
                        'if_back_sn'=> strtoupper($_d1[62]) == 'X' ? 1 : 0
                    ];
                    $warehouseOutSonModel->createBy($warehouse_out_son_data);
                }
            }
            Db::commit();
            writeOperationLogByCommand( '销售发货单成功' ,'EDI/EdiToCross/SUCCESS/SD003Oj');
        }catch (\Exception $e ){
            Db::rollback();
            writeOperationLogByCommand( '销售发货单失败' . $e->getMessage()  . json_encode($data,JSON_UNESCAPED_UNICODE) ,'EDI/EdiToCross/ERROR/SD003Oj');
        }
    }

    //其他发货
    private function SD032Oj($data){
        ini_set('memory_limit', '4086M');

        Db::startTrans();
        try {
            // 使用array_reduce进行分组
            $chunk_data = array_reduce($data, function($reduce_arr, $item) {
                $item_code = $item[0];
                $reduce_arr[$item_code][] = $item;
                return $reduce_arr;
            }, []);

            //dd($chunk_data);

            foreach ($chunk_data as $_code => $_data){
                $warehouseOutModel = new WarehouseOut;
                //判断业务单号是否存在
                $record_pk =  $warehouseOutModel->where('customer_business_number',$_code)->value('id');
                if($record_pk > 0) continue; //存在

                //判断项目是成都还是西安
                $_project_id = '202406261542166632';
                if(in_array($_data[0][35],[6201,6213,6214,6210])){
                    $_project_id = '202407090933417657';
                }

                $params = [
                    'goods_number'=> (int) array_sum(array_column($_data,33) ),
                    'new_order_date'=>date("Y-m-d"),
                    'project_id'=>['202406261520274958',$_project_id],
                    'transport_type'=>'陆运',
                    'customer_order_type'=>'其他出库',
                    'customer_business_number' => $_code
                ];

                $params['tenant_id'] =10148;
                $params['project_client'] = $params['project_id'][1];
                $params['project_id'] = $params['project_id'][0];
                if(!empty($params['ship_to_city'])){
                    $params['ship_to_city'] = json_encode($params['ship_to_city']);
                }
                if(!empty($params['shipper_city'])){
                    $params['shipper_city'] = json_encode($params['shipper_city']);
                }
                $params['warehouse_out_id'] = $params['tenant_id'] . date('YmdHis');
                $params['edi_json'] = json_encode($_data,JSON_UNESCAPED_UNICODE);

                $warehouseOutSonModel = new WarehouseOutSon;

                $pk = $warehouseOutModel->storeBy($params);

                $out_return = $warehouseOutModel->findBy($pk);
                $warehouse_out_id = $out_return['warehouse_out_id'];

                //出库子单
                $warehouse_out_son_arr  = [];
                foreach ($_data as $_k =>  $_d1){
                    $warehouse_out_son_data = [
//                        'box_number'=>1,
                        'box_number'=>$_d1[33],
                        'number'=>$_d1[33],
//                    'packing_id'=>[$_d1[56],'2024062615184510148'],
                        'warehouse_out_id'=>$warehouse_out_id,
                        'warehousing_select_no'=>[],
                        'tenant_id'=>10148,
                        'goods_name'=>$_d1[31],
                        'goods_id'=> Db::table('db_product')
                                ->where('goods_name',$_d1[31])
                                ->where('tenant_id',10148)
                                ->value('goods_id') ?? '',
                        'packing_id'=>'2024062615184510148',
                        'warehouse_out_son_id'=> '10148' . date('YmdHis') .mt_rand(1000,9999).mt_rand(1000,9999) . $_k,
                        'edi_json' => json_encode($_d1,JSON_UNESCAPED_UNICODE),
                        'if_back_sn'=> strtoupper($_d1[36]) == 'X' ? 1 : 0
                    ];
                    $warehouseOutSonModel->createBy($warehouse_out_son_data);
                }
            }
            Db::commit();
            writeOperationLogByCommand( '其他发货单成功' ,'EDI/EdiToCross/SUCCESS/SD032Oj');
        }catch (\Exception $e ){
            Db::rollback();
            writeOperationLogByCommand( '其他发货单失败' . $e->getMessage()  . json_encode($data,JSON_UNESCAPED_UNICODE) ,'EDI/EdiToCross/ERROR/SD032Oj');
        }
    }

    //一步移仓
    private function MM009Oj($data){
        ini_set('memory_limit', '4086M');

        $tenant_id = 10148;
        Db::startTrans();
        try {
            // 使用array_reduce进行分组
            $chunk_data = array_reduce($data, function($reduce_arr, $item) {
                $item_code = $item[1];
                $reduce_arr[$item_code][] = $item;
                return $reduce_arr;
            }, []);

            $mixedArr = [];
            foreach ($chunk_data as $_code => $_data){
                if($_data[0][40] == '311'){//一步移仓
                    $chunk_data_by_goods = array_reduce($data, function($reduce_arr_goods, $item) {
                        $item_code = $item[38];
                        $reduce_arr_goods[$item_code][] = $item;
                        return $reduce_arr_goods;
                    }, []);

                    foreach ($chunk_data_by_goods as $_by_goods){
                        if(count($_by_goods) != 2){
                            throw new Exception('一步移仓参数错误哦');
                        }
                        $_one_mixed = [
                            'customer_business_number'=>$_by_goods[0][1],//业务编号
                            'transfer_instruction_number'=>$_by_goods[0][0],//指令编码
//                            'location'=>$_by_goods[0][10],//'仓库'
                            'num'=>$_by_goods[0][33],
                            'goods'=>$_by_goods[0][38],
                        ];
                        foreach ($_by_goods as $by_goods_line){
                            if($by_goods_line[5] == 1){//out 出库的仓库
                                $_one_mixed['location_out'] = $by_goods_line[10];
                            }else{//in 入的仓库
                                $_one_mixed['location_in'] = $by_goods_line[10];
                            }
                        }
                        $mixedArr[] = $_one_mixed;
                    }

                    $move_main = [
                        'move_code'=>'YBYC' . $tenant_id . date('YmdHis') . mt_rand(1000,9999) ,
                        'customer_business_number'=>$_code,
                        'number'=>array_sum(array_column($mixedArr,'num')),
                        'move_status'=>2,
                        'tenant_id'=>$tenant_id,
                        'creator_id'=>$tenant_id,
                        'move_number'=>array_sum(array_column($mixedArr,'num')),
                        'edi_json'=>json_encode($_data,JSON_UNESCAPED_UNICODE)
                    ];

                    $move_mainModel = new MoveMain;
                    $move_mainModel->storeBy($move_main);

                    /***
                    //开始根据不同的商品，和数据开始分配数据，或者 拆箱
                    foreach ($mixedArr as $_mix){
                    //                        dd($_mix);
                    //出的仓库，来判断项目
                    $location_out = $_mix['location_out'];
                    $goods_name = $_mix['goods'];
                    $out_num = (int) $_mix['num'];//要出库的数量
                    $move_stock = [];

                    $_project_id = '202406261542166632';//西安
                    if(in_array($location_out,[6201,6213,6214,6210])){//成都
                    $_project_id = '202407090933417657';
                    }

                    $stock_where = [];
                    $stock_where[]=['tenant_id','=',$tenant_id];
                    $stock_where[]=['project_client','=',$_project_id];
                    $stock_where[]=['deleted_at','=',0];
                    //                        $stock_where[]=['goods_name','=',$goods_name];
                    $stock_where[]=['goods_name','=','V501010014'];

                    $stock = new Stock;
                    $stockResult = $stock
                    ->field('*,(Good_Qty + Hold_Qty + NG_Qty)  as total_stock')
                    ->where($stock_where)
                    ->having('total_stock > 0')
                    ->select()->toArray();

                    dd($stockResult);

                    $tray_stock_arr = $box_stock_arr = $slice_stock_arr = [];
                    foreach ($stockResult as $one_stock){
                    //                            if(!empty($one_stock['slice_id'])){//件
                    //                                $slice_stock_arr[] = $one_stock;
                    //                            }
                    if(!empty($one_stock['box_id']) && empty($one_stock['slice_id'])){//箱子
                    $box_stock_arr[] = $one_stock;
                    }
                    if(empty($one_stock['box_id']) && empty($one_stock['slice_id'])){//托盘
                    $tray_stock_arr[] = $one_stock;
                    }
                    }

                    $out_num_sy = $out_num;//默认剩余数量 = 要出库数量
                    if(!empty($box_stock_arr)){
                    if(count($box_stock_arr) >= $out_num){

                    }

                    }




                    //dd($stockResult);
                    }
                     ***/
                }
            }
            Db::commit();
            writeOperationLogByCommand( '一步移仓成功' ,'EDI/EdiToCross/SUCCESS/MM009Oj');
        }catch (\Exception $e ){
            Db::rollback();
            writeOperationLogByCommand( '一步移仓失败' . $e->getMessage()  . json_encode($data,JSON_UNESCAPED_UNICODE) ,'EDI/EdiToCross/ERROR/MM009Oj');
        }
    }

    //拆箱
//    private function split($params){
//        $tenant_id = 10148;
//        $stock_id = $params['stock_id'];
//        $num = $params['num'];
//        $generate_ids = $params['generate_ids'];
//
//        if(empty($num)){
//            throw new  Exception('拆箱/件数量错误');
//        }
//
//        if(empty($generate_ids =  array_unique($generate_ids))){
//            $generate_ids = [];
//        }
//
//        if(!empty($generate_ids) && count($generate_ids) != $num){
//            throw new  Exception('箱号数量不对，或者有重复的箱号');
//        }
//
//        $stock = Stock::where('stock_id',$stock_id)->find();
//
//        if(empty($stock)){
//            throw new  Exception('库存ID错误');
//        }
//
//        if(!empty($stock->slice_id)){
//            throw new  Exception('片库存无法操作');
//        }
//
//        $record_id =  $tenant_id .  date("YmdHis") . mt_rand(10000,99999) . mt_rand(1000,9999);
//        $stock_result = Db::table('db_stock')->where('stock_id',$stock_id)->find();
//
//        Db::startTrans();
//        try {
//            if(empty($stock->box_id) && empty($stock->slice_id)){//拆箱
//                $result = (new Stock)->splitBox($stock_id,$num,$generate_ids);
//
//                //添加库存操作记录--start
//                $inventoryOperationRecordModel = new \catchAdmin\storehouse\model\InventoryOperationRecord();
//                $recordResult = (new InventoryOperationRecord($inventoryOperationRecordModel))->write(InventoryOperationRecord::ORDER_TYPE_CX, "CX" . $record_id,[
//                    'stock_id'=>$stock_id,
//                    'box_number'=>$num,
//                    'ext_json'=>json_encode($stock_result),
//                    'tray_id'=>$stock_result['tray_id'],
//                    'box_id'=>  implode(',',array_values(array_filter(array_column($result,'box_id'))))
//                ]);
//                if(!$recordResult){
//                    Db::rollback();
//                    throw new Exception('[拆箱]库存操作记录创建失败');
//                }
//                //添加库存操作记录--end
//            }
//
//            Db::commit();
//        } catch (\Exception $exception) {
//            Db::rollback();
//        }
//    }

    //入库
    private function asn($raw_data){
        ini_set('memory_limit', '4086M');

        Db::startTrans();
        try {

            // 使用array_reduce进行分组
            $chunk_data = array_reduce($raw_data, function($reduce_arr, $item) {
                $item_code = $item[10]; // 参考编号 = 订单号
                $reduce_arr[$item_code][] = $item;
                return $reduce_arr;
            }, []);

            //dump($chunk_data);die();

            foreach ($chunk_data as $_code => $data111){
                //判断是否存在 业务单号
                $warehousingModel = new Warehousing;
                $record_pk =  $warehousingModel
                    ->where('customer_business_number',$_code)->value('id');
                if($record_pk > 0) continue; //存在

                $xianData = $chengduData = [];

                //同一个业务单号，不同的仓库
                foreach ($data111 as $data222){
                    if(in_array($data222[12],[6201,6213,6214,6210])){//成都
                        $chengduData[] = $data222;
                    }else{
                        $xianData[] = $data222;
                    }
                }

                if(!empty($xianData)){
                    $_project_id = '202406261542166632';//西安
                    $_warehousing_son_config_attribute = '1,7314';

                    $data = $xianData;

                    $params = [
                        'goods_number'=> (int) array_sum(array_column($data,19) ),
                        'new_order_date'=>date("Y-m-d"),
                        'project_client'=>['202406261520274958',$_project_id],
                        'warehousing_config_attribute'=>$_warehousing_son_config_attribute
                    ];
                    // dump($params);die();

                    $params['tenant_id'] =10148;
                    $params['warehousing_id'] =  '10148' .date('YmdHis').rand(1000,9999);
                    $params['project_id'] = $params['project_client'][0];
                    $params['project_client'] = $params['project_client'][1];
                    $params['customer_business_number'] = $_code ;//业务单号
                    $params['edi_json'] = json_encode($data,JSON_UNESCAPED_UNICODE);

                    $pk =  $warehousingModel->storeBy($params);

                    $w_result = $warehousingModel->findBy($pk);
                    $w_id = $w_result['warehousing_id'];

                    $warehousing_son = [];
                    foreach ($data as $d){
                        $warehousing_son[] = [
                            'goods_name'=>$d[15],
                            'number'=>(int) $d[19],
                            'tray_number'=>1,
//                            'box_number'=>1,
                            'box_number'=>(int) $d[19],
                            'packing_id'=>'2024062615184510148',
                            'warehousing_id'=>$w_id,
                            'warehousing_son_config_attribute'=>'1,7314',
                            'edi_json' => json_encode($d,JSON_UNESCAPED_UNICODE)
                        ];
                    }

//                dd($warehousing_son);

                    //$w_result->goods_number = array_sum(array_column($data,'number'));
                    //$w_result->save();
                    $sonModel = new WarehousingSon;
                    //$sonModel->createBy($warehousing_son);

                    foreach ($warehousing_son as $key => &$params){
//            $params['goods_name'] = $params['goods_name'];
                        $params['batch_number']='p'.date('YmdHis').mt_rand(1000,9999) . mt_rand(1000,9999);
                        $params['goods_id']=Db::table('db_product')->where('goods_name',$params['goods_name'])->value('goods_id');
                        $params['tenant_id'] = 10148;
                        $params['warehousing_son_id'] ='10148'.date('YmdHis').mt_rand(1000,9999) . mt_rand(1000,9999);
                        $params['enter_type']=1;
                        $params['type'] = 'add';
                        //dd($params);
                        //$params = $this->goods_info($params);

                        $info = DB::name('db_product')
                            ->field('barcode,goods_name,goods_Ename,goods_Cname,supplier_id,manufacturer_id,HSCODE')
                            ->where(['goods_id'=>$params['goods_id']])
                            ->find();

                        $son_data = $params;
                        $son_data['HSCODE'] = $info['HSCODE'];
                        $son_data['goods_name'] = $info['goods_name'];
                        $son_data['goods_Ename'] = $info['goods_Ename'];
                        $son_data['goods_Cname'] = $info['goods_Cname'];
                        $son_data['supplier_id'] = $info['supplier_id'];
                        $son_data['manufacturer_id'] = $info['manufacturer_id'];

                        $where3['supplier_id'] = $info['supplier_id'];
                        $where3['deleted_at'] = 0;

                        $son_data['supplier_name'] = DB::name('db_supplier')->where($where3)->value('supplier_name');

                        $where4['manufacturer_id'] = $info['manufacturer_id'];
                        $where4['deleted_at'] = 0;

                        $son_data['manufacturer_name'] = DB::name('db_manufacturer')->where($where4)->value('manufacturer_name');

                        //包装
                        $where5['packing_id'] = $params['packing_id'];
                        $where5['deleted_at'] = 0;

                        $packing = DB::name('db_packing')
                            ->field('packing_id,packing_num,unit_name')
                            ->where($where5)
                            ->find();

                        $son_data['p_barcode'] = $packing['packing_id'];
                        $son_data['packing_num'] = $packing['packing_num'];
                        $son_data['unit_name'] = $packing['unit_name'];

                        //2。更新子订单表
//                    dd($params);
                        $pk = $sonModel->createBy($son_data);
                    }
                }

                if(!empty($chengduData)){
                    $_project_id = '202407090933417657';
                    $_warehousing_son_config_attribute = '1,7315';

                    $data = $chengduData;

                    $params = [
                        'goods_number'=> (int) array_sum(array_column($data,19)),
                        'new_order_date'=>date("Y-m-d"),
                        'project_client'=>['202406261520274958',$_project_id],
                        'warehousing_config_attribute'=>$_warehousing_son_config_attribute
                    ];
                    // dump($params);die();

                    $params['tenant_id'] =10148;
                    $params['warehousing_id'] =  '10148' .date('YmdHis').rand(1000,9999);
                    $params['project_id'] = $params['project_client'][0];
                    $params['project_client'] = $params['project_client'][1];
                    $params['customer_business_number'] = $_code ;//业务单号
                    $params['edi_json'] = json_encode($data,JSON_UNESCAPED_UNICODE);

                    $pk =  $warehousingModel->createBy($params);

                    $w_result = $warehousingModel->findBy($pk);
                    $w_id = $w_result['warehousing_id'];

                    $warehousing_son = [];
                    foreach ($data as $d){
                        $warehousing_son[] = [
                            'goods_name'=>$d[15],
                            'number'=>(int) $d[19],
                            'tray_number'=>1,
//                            'box_number'=>1,
                            'box_number'=>(int) $d[19],
                            'packing_id'=>'2024062615184510148',
                            'warehousing_id'=>$w_id,
                            'warehousing_son_config_attribute'=>'1,7315',
                            'edi_json' => json_encode($d,JSON_UNESCAPED_UNICODE)
                        ];
                    }

//                dd($warehousing_son);

                    //$w_result->goods_number = array_sum(array_column($data,'number'));
                    //$w_result->save();
                    $sonModel = new WarehousingSon;
                    //$sonModel->createBy($warehousing_son);

                    foreach ($warehousing_son as $key => &$params){
//            $params['goods_name'] = $params['goods_name'];
                        $params['batch_number']='p'.date('YmdHis').mt_rand(1000,9999) . mt_rand(1000,9999);
                        $params['goods_id']=Db::table('db_product')->where('goods_name',$params['goods_name'])->value('goods_id');
                        $params['tenant_id'] = 10148;
                        $params['warehousing_son_id'] ='10148'.date('YmdHis').mt_rand(1000,9999) . mt_rand(1000,9999);
                        $params['enter_type']=1;
                        $params['type'] = 'add';
                        //dd($params);
                        //$params = $this->goods_info($params);

                        $info = DB::name('db_product')
                            ->field('barcode,goods_name,goods_Ename,goods_Cname,supplier_id,manufacturer_id,HSCODE')
                            ->where(['goods_id'=>$params['goods_id']])
                            ->find();

                        $son_data = $params;
                        $son_data['HSCODE'] = $info['HSCODE'];
                        $son_data['goods_name'] = $info['goods_name'];
                        $son_data['goods_Ename'] = $info['goods_Ename'];
                        $son_data['goods_Cname'] = $info['goods_Cname'];
                        $son_data['supplier_id'] = $info['supplier_id'];
                        $son_data['manufacturer_id'] = $info['manufacturer_id'];

                        $where3['supplier_id'] = $info['supplier_id'];
                        $where3['deleted_at'] = 0;

                        $son_data['supplier_name'] = DB::name('db_supplier')->where($where3)->value('supplier_name');

                        $where4['manufacturer_id'] = $info['manufacturer_id'];
                        $where4['deleted_at'] = 0;

                        $son_data['manufacturer_name'] = DB::name('db_manufacturer')->where($where4)->value('manufacturer_name');

                        //包装
                        $where5['packing_id'] = $params['packing_id'];
                        $where5['deleted_at'] = 0;

                        $packing = DB::name('db_packing')
                            ->field('packing_id,packing_num,unit_name')
                            ->where($where5)
                            ->find();

                        $son_data['p_barcode'] = $packing['packing_id'];
                        $son_data['packing_num'] = $packing['packing_num'];
                        $son_data['unit_name'] = $packing['unit_name'];

                        //2。更新子订单表
//                    dd($params);
                        $pk = $sonModel->createBy($son_data);
                    }
                }
            }

            Db::commit();
            writeOperationLogByCommand( '入库单成功' ,'EDI/EdiToCross/SUCCESS/asn');
        }catch (\Exception $e ){
            Db::rollback();
            writeOperationLogByCommand( '入库单失败' .$e->getMessage() . "【数据】"  . json_encode($raw_data,JSON_UNESCAPED_UNICODE) ,'EDI/EdiToCross/ERROR/asn');
        }
    }

//    private function asn1($data,$project_client){
//
//    }


    public function goods_info($params){
        //入库数量对比
        $where1['warehousing_id'] = $params['warehousing_id'];
        $where1['deleted_at'] = 0;
        $goods_number = DB::name('db_warehousing')->where($where1)->value('goods_number');
        if($params['type'] === 'edit'){
            $where[] = ['id','<>',$params['id']];
        }

        $where[] = ['warehousing_id','=',$params['warehousing_id']];
        $where[] = ['deleted_at','=',0];

        $number = Db::name('db_warehousing_son')->field('SUM(number) as number')->where($where)->find();

        $number1 = intval($number['number']) + intval($params['number']);

        if($number1 > $goods_number){
            return array('code'=>0,'msg'=>'商品数量大于商品总数量，请核对商品数量');
        }

        //商品
        $where2['goods_id'] = $params['goods_id'];
//            $where2['deleted_at'] = 0;
        $info = DB::name('db_product')
            ->field('barcode,goods_name,goods_Ename,goods_Cname,supplier_id,manufacturer_id,HSCODE')
            ->where($where2)
            ->find();

        $params['HSCODE'] = $info['HSCODE'];
        $params['goods_name'] = $info['goods_name'];
        $params['goods_Ename'] = $info['goods_Ename'];
        $params['goods_Cname'] = $info['goods_Cname'];
        $params['supplier_id'] = $info['supplier_id'];
        $params['manufacturer_id'] = $info['manufacturer_id'];
        $where3['supplier_id'] = $info['supplier_id'];
        $where3['deleted_at'] = 0;
        $params['supplier_name'] = DB::name('db_supplier')->where($where3)->value('supplier_name');
        $where4['manufacturer_id'] = $info['manufacturer_id'];
        $where4['deleted_at'] = 0;
        $params['manufacturer_name'] = DB::name('db_manufacturer')->where($where4)->value('manufacturer_name');

        //包装
        $where5['packing_id'] = $params['packing_id'];
        $where5['deleted_at'] = 0;
        $packing = DB::name('db_packing')
            ->field('packing_id,packing_num,unit_name')
            ->where($where5)
            ->find();

        $params['p_barcode'] = $packing['packing_id'];
        $params['packing_num'] = $packing['packing_num'];
        $params['unit_name'] = $packing['unit_name'];

        unset($params['type']);
        return array('code'=>1,'msg'=>'','data'=>$params);
    }
}